package com.zzyy.study;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @auther zzyy
 * @create 2024-04-19 18:01
 */
public class ThreadLocalDemoV2
{
    private static ThreadLocal<String> threadLocal = new ThreadLocal<>();
    private static InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();

    public static void main(String[] args)
    {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        try
        {
            threadPool.execute(() -> {
                try {
                    threadLocal.set(Thread.currentThread().getName());
                    System.out.println("value1: "+threadLocal.get());
                } finally {
                    //threadLocal.remove();
                }
            });

            System.out.println("-----------------");

            threadPool.execute(() -> {
                try {
                    threadLocal.set(Thread.currentThread().getName());
                    System.out.println("value2: "+threadLocal.get());
                } finally {
                    threadLocal.remove();
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }

        //暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        System.out.println("==============ThreadLocal");
        System.out.println();
        threadLocal.set(Thread.currentThread().getName());
        System.out.println("ThreadLocal主线程get()："+threadLocal.get());

        new Thread(() -> {
            System.out.println("ThreadLocal子线程get()："+threadLocal.get());
        },"t1").start();
        System.out.println();

        //暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        System.out.println("==============InheritableThreadLocal");
        System.out.println();
        inheritableThreadLocal.set(Thread.currentThread().getName());
        System.out.println("主线程："+inheritableThreadLocal.get());

        new Thread(() -> {
            System.out.println("子线程："+inheritableThreadLocal.get());
        },"t2").start();
    }
}
